<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isVerified ? '实名认证信息' : '实名认证'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 已认证状态展示 -->
    <template v-if="isVerified">
      <div class="verified-info">
        <div class="status-icon">
          <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        </div>
        <h3 class="verified-title">已完成实名认证</h3>
        <div class="info-item">
          <span class="label">真实姓名：</span>
          <span class="value">{{ maskName(identityInfo.realName) }}</span>
        </div>
        <div class="info-item">
          <span class="label">身份证号：</span>
          <span class="value">{{ maskIdCard(identityInfo.idCard) }}</span>
        </div>
        <div class="info-item">
          <span class="label">认证时间：</span>
          <span class="value">{{ identityInfo.verifyTime }}</span>
        </div>
      </div>
    </template>

    <!-- 未认证状态表单 -->
    <template v-else>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="verify-form"
      >
        <!-- 认证说明 -->
        <div class="verify-tips">
          <el-alert
            title="请填写真实身份信息，认证后不可修改"
            type="warning"
            description="我们将对您的个人信息进行严格保密，仅用于身份验证"
            :closable="false"
            show-icon
          />
        </div>

        <!-- 真实姓名 -->
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="form.realName"
            placeholder="请输入真实姓名"
            maxlength="20"
          />
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="form.idCard"
            placeholder="请输入18位身份证号码"
            maxlength="18"
          />
        </el-form-item>

        <!-- 身份证照片 -->
        <el-form-item label="身份证照片" required>
          <div class="upload-section">
            <!-- 正面照片 -->
            <div class="upload-item">
              <el-form-item prop="frontImage">
                <el-upload
                  class="id-card-uploader"
                  action="/api/upload/idcard"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="(res) => handleUploadSuccess(res, 'front')"
                >
                  <img
                    v-if="form.frontImage"
                    :src="form.frontImage"
                    class="uploaded-image"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <div class="upload-text">上传身份证正面</div>
                  </div>
                </el-upload>
              </el-form-item>
              <div class="upload-tips">请上传身份证人像面</div>
            </div>

            <!-- 反面照片 -->
            <div class="upload-item">
              <el-form-item prop="backImage">
                <el-upload
                  class="id-card-uploader"
                  action="/api/upload/idcard"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="(res) => handleUploadSuccess(res, 'back')"
                >
                  <img
                    v-if="form.backImage"
                    :src="form.backImage"
                    class="uploaded-image"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <div class="upload-text">上传身份证反面</div>
                  </div>
                </el-upload>
              </el-form-item>
              <div class="upload-tips">请上传身份证国徽面</div>
            </div>
          </div>
        </el-form-item>

        <!-- 隐私协议 -->
        <el-form-item prop="agreement">
          <el-checkbox v-model="form.agreement">
            我已阅读并同意
            <el-button type="primary" link @click="showAgreement">
              《实名认证服务协议》
            </el-button>
          </el-checkbox>
        </el-form-item>
      </el-form>
    </template>

    <!-- 操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">
          {{ isVerified ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!isVerified"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          提交认证
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CircleCheckFilled, Plus } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  isVerified: {
    type: Boolean,
    default: false,
  },
  identityInfo: {
    type: Object,
    default: () => ({
      realName: "",
      idCard: "",
      verifyTime: "",
    }),
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const formRef = ref(null);
const loading = ref(false);

const form = ref({
  realName: "",
  idCard: "",
  frontImage: "",
  backImage: "",
  agreement: false,
});

// 表单校验规则
const rules = {
  realName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, message: "姓名长度不能小于2个字符", trigger: "blur" },
  ],
  idCard: [
    { required: true, message: "请输入身份证号码", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
      trigger: "blur",
    },
  ],
  frontImage: [
    { required: true, message: "请上传身份证正面照片", trigger: "change" },
  ],
  backImage: [
    { required: true, message: "请上传身份证反面照片", trigger: "change" },
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请阅读并同意实名认证服务协议"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 处理上传成功
const handleUploadSuccess = (response, type) => {
  if (type === "front") {
    form.value.frontImage = response.url;
  } else {
    form.value.backImage = response.url;
  }
  ElMessage.success("上传成功");
};

// 显示协议
const showAgreement = () => {
  ElMessageBox.alert(
    "这里是实名认证服务协议的具体内容...",
    "实名认证服务协议",
    {
      confirmButtonText: "我知道了",
    },
  );
};

// 提交认证
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    // TODO: 调用实名认证API
    await new Promise((resolve) => setTimeout(resolve, 1000));

    ElMessage.success("实名认证提交成功，请等待审核");
    emit("success", form.value);
    dialogVisible.value = false;
  } catch (error) {
    console.error(error);
    ElMessage.error("表单验证失败");
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  formRef.value?.resetFields();
  form.value = {
    realName: "",
    idCard: "",
    frontImage: "",
    backImage: "",
    agreement: false,
  };
};

// 姓名脱敏
const maskName = (name) => {
  if (!name) return "";
  return name.charAt(0) + "*".repeat(name.length - 1);
};

// 身份证号脱敏
const maskIdCard = (idCard) => {
  if (!idCard) return "";
  return idCard.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2");
};
</script>

<style lang="scss" scoped>
.verify-form {
  @apply p-4;

  .verify-tips {
    @apply mb-6;
  }
}

.verified-info {
  @apply text-center py-6;

  .status-icon {
    @apply mb-4;

    .success-icon {
      @apply text-5xl text-green-500;
    }
  }

  .verified-title {
    @apply text-xl font-medium text-gray-900 mb-6;
  }

  .info-item {
    @apply flex items-center justify-center py-2;

    .label {
      @apply text-gray-500;
    }

    .value {
      @apply text-gray-900 ml-2;
    }
  }
}

.upload-section {
  @apply flex gap-6;

  .upload-item {
    @apply flex-1;

    .id-card-uploader {
      :deep(.el-upload) {
        @apply w-full border border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-primary-500;
      }

      .uploaded-image {
        @apply w-full h-48 object-cover rounded-lg;
      }

      .upload-placeholder {
        @apply h-48 flex flex-col items-center justify-center;

        .el-icon {
          @apply text-3xl text-gray-400 mb-2;
        }

        .upload-text {
          @apply text-sm text-gray-500;
        }
      }
    }

    .upload-tips {
      @apply mt-2 text-center text-sm text-gray-500;
    }
  }
}

.dialog-footer {
  @apply flex justify-end gap-2;
}
</style>
